// pages/product/detail.js
import api from '../../api/index'
import { AppId } from '../../api/config'
import { userInfoStore } from '../../store/userInfo'
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLevel: 0,
    product:null,
    topImages:[],
    detailImages:[],
    canUseCoupons: null,
    scope:null,
    maskHidden:false,
    showSkuType:0,
    skuGroup:null,
    skus: null,
    selectSku: null,
    selectSkuArr:[],
    buyNumber:1,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ userLevel: userInfoStore.userInfo.level })
    this.getProductDetail(options.id);
    
    this.getScope(options.id);
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  getScope: function(id){
    let self = this
    api.getScope({ productId: id }).then(res => {
      let { result } = res;
      let sp = [],s,rds;
      for (let i = 0; i < result.length; i++) {
        rds = result[i];
        s = '';
        if(rds.province == rds.city) {
          s = rds.province;
        } else if (rds.city){
          s = rds.province + rds.city;
        } else {
          s = rds.province;
        }
        if (rds.district) s += rds.district;
        sp.push(s);
      }
      self.setData({ scope: sp.join('、')})
    });
  },

  getProductSkus: function (id) {
    let self = this
    api.getProductSkus({ productId: id }).then(res => {
      let { result } = res;
      let spec = self.data.product.spec.split("/");
      let values=[];
      for (let i = 0; i < spec.length; i++) {
        let rds = {title: spec[i], item:[]}
        values.push(rds);
      }
      for (let i = 0; i < result.length; i++) {
        let rds = result[i];
        let sn = rds.skuName.split("/");

        if (spec.length != sn.length) break;
        for (let j=0; j< sn.length; j++) {
          let obj = values[j];
          let find = false;
          for (let m = 0; m < obj.item.length; m++) {
            if (obj.item[m].text==sn[j]) {
              find =true;
              break;
            }
          }
          if (!find) obj.item.push({text:sn[j], isSet: true});
        }
      }
      self.setData({
        skus: result,
        skuGroup: values
      },()=>{
        // console.log(self.data.skus)
        // console.log(self.data.skuGroup)
      });
    })
  },

  getProductDetail:function(id){
    let self=this
    api.getproductdetail({ productId:id}).then(res=>{
      let {result} = res;
      let a1 = [];
      let a2 = [];
      for (let i = 0; i < result.images.length;i++){

          if(result.images[i].imageType==2){
            a1.push(result.images[i])
          }
          if (result.images[i].imageType >= 3) {
            a2.push(result.images[i])
          }
      }
      self.setData({
        product: result,
        topImages: a1,
        detailImages: a2
      },()=>{
        if (self.data.product.spec && self.data.product.spec.length>0){
          self.getProductSkus(id);
        }
      });
      

    })
  },

  getPhoneNumber: function (e) {
    // console.log(e);
    if (e.detail.iv) {
      let { session_key } = userInfoStore.userInfo;
      let pc = new WXBizDataCrypt(AppId, session_key);
      var ret = pc.decryptData(e.detail.encryptedData, e.detail.iv)
      console.log('解密后 data: ', ret)
      var param = {
        openId: userInfoStore.userInfo.openId,
        phone: ret.phoneNumber,
        level: 1
      }
      var self = this;
      if (app.globalData.inviteCode)
      param = Object.assign(param, { recomendCode: app.globalData.inviteCode })
      api.saveUser(param).then(res => {
        let { userInfo } = userInfoStore;
        let { result } = res;
        result.session_key = userInfo.session_key;
        userInfoStore.updateUserInfo(result);
        
        self.buy();
      }, err => {
        wx.showModal({
          title: "提交失败",
          content: err,
          showCancel: false,
          confirmText: "我知道了"
        })
      });
    }
  },

  showSku:function(){
    this.setData({ 
      maskHidden: true,
      showSkuType: 0
    });
  },

  hideSku:function(){
    this.setData({ maskHidden: false });
  },

  clickSku:function(e){
    let index = e.currentTarget.dataset.gdx;
    let value = e.currentTarget.dataset.item.text;
    this.data.selectSkuArr[index] = value;
    let self = this
    this.setData({
      selectSkuArr: this.data.selectSkuArr
    }, () => {
      // console.log(JSON.stringify(this.data.selectSkuArr))
      let allSelect = true;
      for (let i = 0; i < self.data.selectSkuArr.length; i++){
        if (!self.data.selectSkuArr[i]){
          allSelect = false;
          break;
        }
      }
      if (self.data.selectSkuArr.length != self.data.skuGroup.length) allSelect=false;
      if(allSelect){
        let skuStr = self.data.selectSkuArr.join('/');
        let have = false;
        let selectData = null;
        for (let j = 0; j < self.data.skus.length; j++) {
          let rds = self.data.skus[j];
          if (rds.skuName == skuStr) {
            selectData = rds;
            break;
          }
        }
        if (selectData)
          self.setData({ selectSku: selectData })
        else
          self.setData({ selectSku: null })
        self.checkLabel();
      }
    })
  },

  checkLabel: function () {//红色/32/aa 

    // let sn = this.data.selectSku.split('/');
    let sn = this.data.selectSkuArr;
    for (let i = 0; i < sn.length; i++) {
      for (let m = 0; m < this.data.skuGroup[i].item.length; m++) {
        let sku = []

        for (let e = 0; e < i; e++) {
          sku.push(sn[e])
        }
        sku.push(this.data.skuGroup[i].item[m].text);
        for (let f = i + 1; f < sn.length; f++) {
          sku.push(sn[f])
        }
        //console.log(JSON.stringify(sku));
        let skustr = sku.join('/');
        let find = false;
        for (let j = 0; j < this.data.skus.length; j++) {
          let rds = this.data.skus[j];
          if (rds.skuName == skustr) {
            find = true;
            break;
          }
        }
        if (!find)
          this.data.skuGroup[i].item[m].isSet = false;
        else
          this.data.skuGroup[i].item[m].isSet = true;
      }
    }
    //console.log(JSON.stringify(this.data.skuGroup));
    this.setData({
      skuGroup: this.data.skuGroup
    })

  },

  raiseNumber: function (e) {
    let num = parseInt(this.data.buyNumber);
    if (num == this.data.selectSku.stock) return;
    num++;
    this.setData({
      buyNumber: num,
      
    })
  },

  reduceNumber: function (e) {
    let num = parseInt(this.data.buyNumber);
    if (num == 1) return;
    num--;
    this.setData({
      buyNumber: num,
    })
  },

  buySku:function(){
    
    if (!this.data.product) return;
    if (this.data.product.status != 1) {
      wx.showToast({
        icon: "none",
        title: '商品已下架,敬请期待...',
      });
      return;
    }
    let p = this.data.product;
    let today = new Date();
    if (p.buyBeginTime) {
      let beginStr = p.buyBeginTime.substring(0, 19).replace(/-/g, '/');
      let begin = new Date(beginStr);
      if (today - begin < 0) {
        // console.log(beginStr);
        let msg = (begin.getMonth() + 1) + '月' + begin.getDate() + '日' + begin.getHours() + '点,不见不散呦~';
        wx.showToast({
          icon: "none",
          title: msg
        })
        return;
      }
    }
    if (p.buyEndTime) {
      let endStr = p.buyEndTime.substring(0, 19).replace(/-/g, '/');
      let end = new Date(endStr);
      if (today - end > 0) {
        // console.log(today - end);
        wx.showToast({
          icon: "none",
          title: "更多精彩敬请期待!"
        })
        return;
      }
    }
    if (!this.data.selectSku){
      wx.showToast({
        icon: "none",
        title: '请选择规格...',
      });
      return;
    }
    wx.navigateTo({
      url: 'buy?id=' + this.data.product.id + '&sku=' + JSON.stringify(this.data.selectSku) + '&num=' + this.data.buyNumber
    })

  },

  buy:function(){
    if (!this.data.product) return;
    if (this.data.product.status != 1) {
      wx.showToast({
        icon: "none",
        title: '商品已下架,敬请期待...',
      });
      return;
    }
    if (this.data.skus && this.data.skus.length > 0) {
      this.setData({
        maskHidden: true,
        showSkuType: 1
      });
      return;
    } 
    let p = this.data.product;
    let today = new Date();
    if (p.buyBeginTime) {
      let beginStr = p.buyBeginTime.substring(0, 19).replace(/-/g, '/');
      let begin = new Date(beginStr);
      if (today - begin < 0) {
        let msg = (begin.getMonth() + 1) + '月' + begin.getDate() + '日' + begin.getHours() + '点,不见不散呦~';
        
        // console.log(beginStr);

        wx.showToast({
          icon: "none",
          title: msg
        })
        return;
      }
    }
    if (p.buyEndTime) {
      let endStr = p.buyEndTime.substring(0, 19).replace(/-/g, '/');
      let end = new Date(endStr);
      if (today - end > 0) {
        // console.log(today - end);
        wx.showToast({
          icon: "none",
          title: "更多精彩敬请期待!"
        })
        return;
      }
    }
    
    wx.navigateTo({
      url: 'buy?id=' + this.data.product.id
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getApp().share();
  }
})